﻿CREATE PROCEDURE [dbo].[proc_Company_Range_Create]
	(
		@UserName nvarchar(50),
		@EName nvarchar(50),
		@UpName nvarchar(50),
		@UpDate datetime,
		@IsAll bit,
		@CompanyList nvarchar(500)
	)
AS
begin
	Declare @CompanyId int
	Select @CompanyId=CompanyId From Employee Where UserName=@UserName
	Insert Into Company_RangeUsers(UserName,EName,CompanyId,UpName,[UpDate],IsAll)
	Values(@UserName,@EName,@CompanyId,@UpName,@UpDate,@IsAll)
	declare @ParentId int,@i int,@Sort int
	Select @ParentId=@@Identity
	Set @i=0
	while(@i<len(@CompanyList))
	begin
		if(substring(@CompanyList,@i,charindex(',',@CompanyList,@i)-@i)=@CompanyId)
			begin
				Set @Sort=1
			end
		else
			begin
				Set @Sort=2
			end
		Insert Into Company_Range(ParentId,CompanyId,UserName,Sort)Values(@ParentId, substring(@CompanyList,@i,charindex(',',@CompanyList,@i)-@i),@UserName,@Sort)
		Set @i=charindex(',',@CompanyList,@i)+1
	end
end
	RETURN
